<template>
  <div class="login_container">
    <el-row>
      <el-col :xs="0" :span="12"></el-col>
      <el-col :xs="24" :span="12">
        <el-form
          ref="ruleFormRef"
          class="login_form"
          :model="loginForm"
          label-width="auto"
          style="max-width: 450px"
        >
          <el-form-item label="用户名">
            <el-input :prefix-icon="User" v-model="loginForm.username" />
          </el-form-item>
          <el-form-item label="密码">
            <el-input
              :prefix-icon="Lock"
              type="password"
              show-password
              v-model="loginForm.password"
            />
          </el-form-item>
          <el-form-item>
            <el-button
              class="login_btn"
              type="primary"
              @click="login(ruleFormRef)"
            >
              登录
            </el-button>
          </el-form-item>
        </el-form>
      </el-col>
    </el-row>
  </div>
</template>

<script lang="ts" setup>
import { reactive, ref } from 'vue'
import { User, Lock } from '@element-plus/icons-vue' // element-plus图标
import { ElNotification } from 'element-plus'
import type { FormInstance } from 'element-plus'
import { useUserStore } from '@/store/modules/user' // 引入pinia
import { useRouter, useRoute } from 'vue-router'
let $router = useRouter()
let $route = useRoute()
const ruleFormRef = ref<FormInstance>()
const userStore = useUserStore()
const { userLogin } = userStore
const loginForm = reactive({
  username: 'admin',
  password: '111111',
})

const login = async () => {
  try {
    await userLogin(loginForm)
    // 判断跳转到login页的时候是否携带路由参数，有登录成功后就跳转到该路由
    let recirect: any = $route.query.redirect
    $router.push({ path: recirect || '/' }) // 登录成功跳转
    ElNotification({
      type: 'success',
      message: '登录成功',
    })
  } catch (error) {
    ElNotification({
      type: 'error',
      message: (error as Error).message,
    })
  }
}
</script>
<style lang="scss" coped>
.login_container {
  width: 100%;
  height: 100%;
  margin: 0;
  padding: 0;
  .login_form {
    margin: 0 auto;
    top: 20vh;
    text-align: center;
    .login_btn {
      width: 100%;
    }
  }
}
</style>
